# coding:utf-8
import os
import sys
import json
import collections
import shutil
import subprocess
from tools.templates.prebuild import Pre_build
from tools.templates.postbuild import Post_build
from tools.OTA.tl_check_fw import OTA_build

# Parameter description:
# $1 - Application project path: apps/tuyaos_zigbee_light_sample
# $2 - Application project name: tuyaos_zigbee_light_sample
# $3 - Application project version: 1.0.0
# $4 - Application project command: build or clean
# python3 build_app.py apps/tuyaos_zigbee_light_sample tuyaos_zigbee_light_sample 1.0.0 clean

# Get the path to the current python interpreter
PYTHON_PATH = sys.executable

APP_PATH = sys.argv[1]
APP_PATH = APP_PATH.replace('\\','/') 
APP_NAME = sys.argv[2]
APP_VERSION = sys.argv[3]
BUILD_COMMAND = 'build'

if len(sys.argv) == 5:
    BUILD_COMMAND = sys.argv[4]

# app project product name and path
CURR_PATH = os.getcwd()
ROOT_PATH = CURR_PATH
APP_BUILD_PATH = os.path.join(APP_PATH, '_build')
APP_INCLUDE_PATH = os.path.join(APP_PATH, 'include')
APP_SRC_PATH = os.path.join(APP_PATH, 'src')


# firmware info parser
def device_type_info_collect():
    global DEV_TYPE
    print("firmware information parse start...")
    file = open(os.path.join(APP_PATH, 'appconfig.json'), 'rb')
    fileJson = json.load(file, object_pairs_hook=collections.OrderedDict)
    DEV_TYPE = fileJson['firmwareInfo']['dev_role']
    file.close()
    if ('router'==DEV_TYPE) or ('sleep_end_dev'==DEV_TYPE):
        print("firmware information parse success")
        print(DEV_TYPE)
    else:
        print("firmware information dev_role parse fail")


# check 
if len(sys.argv) < 3 or APP_PATH=='' or APP_NAME=='' or APP_VERSION=='':
    print("Script parameter error !!!")

COPY_SOURCE_PATH = os.path.join(ROOT_PATH, 'tools/templates/')
APP_FOLDER_PATH = os.path.join(ROOT_PATH, APP_PATH)
BUILD_APP_JSON_NAME = os.path.join(APP_FOLDER_PATH, 'appconfig.json')
APP_JSON_SOURCE = os.path.join(COPY_SOURCE_PATH, 'appconfig.json')

if not os.path.exists(APP_PATH):
    print(APP_PATH + "not exist!!!")
    sys.exit(1)

if BUILD_COMMAND == "build":

    if not os.path.exists(APP_INCLUDE_PATH):
        os.makedirs(APP_INCLUDE_PATH)

    if not os.path.exists(APP_SRC_PATH):
        os.makedirs(APP_SRC_PATH)

    if not os.path.isfile(BUILD_APP_JSON_NAME): 
        print("app_config.json not exist, copy app_config.json to app folder...")
        shutil.copy(APP_JSON_SOURCE, APP_FOLDER_PATH)

    device_type_info_collect()
        
    os.chdir('tools/templates')

    Pre_build()
    Post_build(DEV_TYPE, BUILD_COMMAND)
    OTA_build(APP_PATH,APP_NAME,'tc32',APP_VERSION)

    # python_path = 'python3 prebuild.py'
    # para = "%s \"%s\" \"%s\" \"%s\""%(python_path, APP_PATH, APP_NAME, APP_VERSION)
    # ret = subprocess.call(para)
    # if ret != 0:
    #     print("prebuild.py execution failed !!!")
    #     sys.exit(1)

    # python_path = 'python3 postbuild.py'
    # para = "%s \"%s\" \"%s\" \"%s\" \"%s\" %s\""%(python_path, APP_PATH, APP_NAME, APP_VERSION, DEV_TYPE, BUILD_COMMAND)
    # ret = subprocess.call(para)
    # if ret != 0:
    #     print("postbuild.py execution failed !!!")
    #     sys.exit(1)

    os.chdir(CURR_PATH)

elif BUILD_COMMAND == "clean":

    os.chdir('tools/templates')
    Post_build('', BUILD_COMMAND)
    os.chdir(CURR_PATH)

